/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.texture;

import com.android1.amarena2d.commons.Provider;
import com.android1.amarena2d.engine.ContextManager;
import com.badlogic.gdx.graphics.Pixmap;


public class ManagedPixmapTexture extends BaseManagedTexture implements ManagedTexture, ContextManager.Listener {


    Provider<Pixmap> provider;

    public ManagedPixmapTexture(Provider<Pixmap> provider) {
        this(provider, TextureOptions.NEAREST);
    }

    public ManagedPixmapTexture(Provider<Pixmap> pixmapProvider, TextureOptions textureOptions) {
        super(new TextureDef(pixmapProvider, textureOptions));
        textureFrame = new TextureFrameImpl(this, 0, 0, 0, 0);
        this.provider = pixmapProvider;
    }


    public void init() {
        if (!init) {
            Pixmap pixmap = provider.get();
            texture = engine.getGraphics().newUnmanagedTexture(pixmap, def.textureOptions.minFilter, def.textureOptions.magFilter, def.textureOptions.uWrap, def.textureOptions.vWrap);

            invTexWidth = 1.0f / texture.getWidth();
            invTexHeight = 1.0f / texture.getHeight();

            if (textureFrame.getWidth() == 0 && textureFrame.getHeight() == 0) {
                textureFrame.set(0, 0, texture.getWidth(), texture.getHeight());
            }

            engine.getContextManager().register(this);

            init = true;
            resourceManager.init();
        }
    }

    public void dispose() {
        if (canDispose()) {
            if (texture != null)
                texture.dispose();
            if (sharedTexturedMesh != null)
                sharedTexturedMesh.dispose();
            engine.getContextManager().unregister(this);
            texture = null;
            sharedTexturedMesh = null;
            init = false;
            resourceManager.dispose();
        }
    }


    @Override
    public void onContextLoss() {
        Pixmap pixmap = provider.get();
        texture = engine.getGraphics().newUnmanagedTexture(pixmap, def.textureOptions.minFilter, def.textureOptions.magFilter, def.textureOptions.uWrap, def.textureOptions.vWrap);

    }
}